package middle.code;

import lombok.extern.slf4j.Slf4j;

/**
 * 有个输出0和1的BIASED RANDOM，它以概率p输出1，以概率1-p输出0。
 * 以此RANDOM函数为基础，生成另一个RANDOM函数，该函数以1/2的概率输出1，以1/2的概率输出0
 */
@Slf4j
public class Code03_Random {
    public static int f1() {
        return Math.random() < 0.8 ? 1 : 0;
    }

    public static int f2() {
        int random1 = -1;
        int random2 = -1;
        do {
            random1 = f1();
            random2 = f1();
        } while ((random1 == 1 && random2 == 1)
                || (random1 == 0 && random2 == 0));
        return random1;
    }

    public static void main(String[] args) {
        int num = 100000;

        // f1()
        int zero1 = 0;
        int one1 = 0;
        for (int i = 0; i < num; i++) {
            if (f1() == 0) {
                zero1++;
            } else {
                one1++;
            }
        }
        log.info("f1, num: {}, zero: {}, one: {}", num, zero1, one1);

        // f2()
        int zero2 = 0;
        int one2 = 0;
        for (int i = 0; i < num; i++) {
            if (f2() == 0) {
                zero2++;
            } else {
                one2++;
            }
        }
        log.info("f2, num: {}, zero: {}, one: {}", num, zero2, one2);
    }
}
